<?php
include 'header.php';
include 'menu.php';

$current = $request->get('type', 'index');
$co = $request->get('co', '');
$title = $current == 'index' ? $menu->title : '邀请码列表 ';


function down($str){
    $ua=$_SERVER["HTTP_USER_AGENT"];
    $filename="邀请码".date('YmdHis',time()).".txt";
    $encoded_filename=urlencode($filename);
    $encoded_filename=str_replace("+","%20",$encoded_filename);
    header("Content-Type:application/octet-stream");
    header("Content-Type: application/force-download");
    header("Accept-Ranges:bytes");
    if(preg_match("/MSIE/",$ua)){
        header('Content-Disposition:attachment;filename="'.$encoded_filename.'"');
    }elseif(preg_match("/Firefox/",$ua)){
        header('Content-Disposition:attachment;filename*="utf8'.$filename.'"');
    }else{
        header('Content-Disposition:attachment;filename="'.$filename.'"');
    }
    ob_end_clean();
    $fp = fopen('php://output', '');
    fwrite($fp,$str);
    fclose($fp);
    die;
}

function dataList($db,$data_name){
    $query = $db->select('code','num','duration')->from("$data_name")
        ->order('id',Typecho_Db::SORT_DESC);
    $result = $db->fetchAll($query);
    return $result;
}
?>

<div class="main">
    <div class="body container">
        <div class="typecho-page-title">
            <h2><?=$title?></h2>
        </div>
        <div class="row typecho-page-main" role="main">
            <div class="col-mb-12">
                <ul class="typecho-option-tabs fix-tabs clearfix">
                    <li<?=($current == 'index' ? ' class="current"' : '')?>><a href="<?php $options->adminUrl('extending.php?panel=' . InvitationCode_Plugin::$panel); ?>"><?php _e('邀请码生成'); ?></a></li>
                    <li<?=($current == 'list' ? ' class="current"' : '')?>><a href="<?php $options->adminUrl('extending.php?panel=' . InvitationCode_Plugin::$panel . '&type=list'); ?>">
                            <?php _e('邀请码列表'); ?>
                        </a></li>
                    <li><a href="<?php $options->adminUrl('options-plugin.php?config=InvitationCode') ?>"><?php _e('插件设置'); ?></a></li>
                </ul>
            </div>

            <?php if ($current == 'index'): ?>
                <div class="typecho-edit-theme">
                    <div class="col-mb-12 col-tb-8 col-9 content">
                        <?php Typecho_Widget::widget('InvitationCode_Console')->generateCodeForm()->render(); ?>
                    </div>
                </div>
            <?php else:
                Typecho_Widget::widget('InvitationCode_Console')->to($files);
                ?>
                <div class="typecho-edit-theme">
                    <div class="col-mb-12 col-tb-8 col-9 content">

                        <ul class="typecho-option typecho-option-submit" id="typecho-option-item--2">
                            <li>
                                <a href="<?php $options->adminUrl('extending.php?panel=' . InvitationCode_Plugin::$panel . '&type=list&co=del_db') ?>"><button type="submit" class="btn primary">删除邀请码数据库</button></a>
                                <a href="<?php $options->adminUrl('extending.php?panel=' . InvitationCode_Plugin::$panel . '&type=list&co=export') ?>"><button type="submit" class="btn primary">导出</button></a>
                            </li>
                        </ul>

                        <table>
                            <thead>
                            <tr>
                                <th width="100">序号</th>
                                <th>邀请码</th>
                                <th width="100">剩余次数</th>
                                <th width="200">过期时间</th>
                            </tr>
                            </thead>
                            <tbody>

                            <?php
                            $db= Typecho_Db::get();
                            $prefix = $db->getPrefix();
                            $getAdapterName = $db->getAdapterName();
                            $data_name=$prefix.'invitation_code';
                            if($co == 'del_db'){
                                $db->query("DROP TABLE IF EXISTS {$data_name}");
                            }
                            $is_t=0;
                            if(preg_match('/^M|m?ysql$/',$getAdapterName)){
                                $query = $db->select('TABLE_NAME')->from("INFORMATION_SCHEMA.TABLES")->where("TABLE_NAME='{$data_name}'");
                                $is_exist = $db->fetchRow($query);
                                if($is_exist){
                                    $is_t=1;
                                }
                            }elseif(preg_match('/^S|s?Q|q?L|l?ite$/',$getAdapterName)){
                                $query = $db->select('name')->from("sqlite_master")->where("name={$data_name}");
                                $is_exist = $db->fetchRow($query);
                                if($is_exist){
                                    $is_t=1;
                                }
                            }elseif(preg_match('/^P|p*?gsql$/is',$getAdapterName)){
                                $query = $db->select('count(*)')->from("pg_class")->where(" relname = '{$data_name}'");
                                $is_exist = $db->fetchRow($query);
                                if($is_exist['count']){
                                    $is_t=1;
                                }
                            }
                            if($co == 'export'){
                                if($is_t){
                                    $result=dataList($db,$data_name);
                                    $str='';
                                    foreach($result as $k=>$v){
                                        $duration=$v['duration'] == 0 ? '永久' : date('Y-m-d H:i:s',$v['duration']);
                                        $str.='邀请码：'.$v['code'].'  剩余次数：'.$v['num'].'  过期时间：'.$duration."\n";
                                    };
                                    down($str);
                                }else{
                                    echo "<script type='text/javascript'>alert('没有邀请码')</script>";
                                }
                            }
                            if($is_t){
                                $result=dataList($db,$data_name);
                                foreach($result as $k=>$v){
                                    $duration=$v['duration'] == 0 ? '永久' : date('Y-m-d H:i:s',$v['duration']);
                                    echo '
                                        <tr align="center">
                                            <td>'.($k+1).'</td>
                                            <td>'.$v['code'].'</td>
                                            <td>'.$v['num'].'</td>
                                            <td>'.$duration.'</td>
                                        </tr>';
                                };
                            }else{
                                echo '
                                <tr align="center">
                                    <td colspan="3">没有邀请码数据库；请先生成邀请码！</td>
                                 </tr>';
                            }
                            ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>


<?php
include 'copyright.php';
include 'common-js.php';
include 'footer.php';
?>

